package com.jdbc.homework;

import java.sql.*;
import java.util.Scanner;

/**
 * @author 1
 * @Description
 * @Date 2025-2-25 17:31
 */
public class PetStoreDemo {

    public static final String URL = "jdbc:mysql://localhost:3306/mydb?serverTimezone=GMT&useUnicode=true&characterEncoding=UTF-8";
    public static final String USER = "root";
    public static final String PASSWORD = "123456";
    private static int currentUserId = -1; // 当前登录用户的ID
    private static boolean isAdmin = false; // 当前用户是否为管理员

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        while (true) {
            System.out.println("\n欢迎来到宠物商店管理系统！");
            System.out.println("1) 登录");
            System.out.println("0) 退出");
            System.out.print("请输入选项: ");
            int choice = scanner.nextInt();
            scanner.nextLine(); // 清除缓冲区

            switch (choice) {
                case 1:
                    login(scanner);
                    if (currentUserId != -1) {
                        showMenu(scanner);
                    }
                    break;
                case 0:
                    System.out.println("退出系统，再见！");
                    return;
                default:
                    System.out.println("无效选项，请重新选择！");
            }
        }
    }

    // 用户登录
    private static void login(Scanner scanner) {
        System.out.print("请输入用户名: ");
        String username = scanner.nextLine();
        System.out.print("请输入密码: ");
        String password = scanner.nextLine();

        String sql = "SELECT id, is_admin FROM p_user WHERE username = ? AND password = ?";
        try (Connection conn = DriverManager.getConnection(URL, USER, PASSWORD);
             PreparedStatement ps = conn.prepareStatement(sql)) {
            ps.setString(1, username);
            ps.setString(2, password);
            ResultSet rs = ps.executeQuery();
            if (rs.next()) {
                currentUserId = rs.getInt("id");
                isAdmin = rs.getBoolean("is_admin");
                System.out.println("登录成功！");
            } else {
                System.out.println("登录失败，用户名或密码错误！");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    // 显示菜单
    private static void showMenu(Scanner scanner) {
        while (true) {
            System.out.println("\n请选择操作：");
            System.out.println("1) 查看所有宠物");
            System.out.println("2) 购买宠物");
            if (isAdmin) {
                System.out.println("3) 添加宠物");
                System.out.println("4) 删除宠物");
                System.out.println("5) 更新宠物信息");
                System.out.println("6) 查看所有用户");
            }
            System.out.println("0) 退出登录");
            System.out.print("请输入选项: ");
            int choice = scanner.nextInt();
            scanner.nextLine(); // 清除缓冲区

            switch (choice) {
                case 1:
                    showAllPets(scanner);
                    break;
                case 2:
                    buyPets(scanner);
                    break;
                case 3:
                    addPet(scanner);
                    break;
                case 4:
                    deletePet(scanner);
                    break;
                case 5:
                    updatePet(scanner);
                    break;
                case 6:
                    showAllUsers();
                    break;
                case 0:
                    currentUserId = -1;
                    isAdmin = false;
                    System.out.println("已退出登录！");
                    return;
                default:
                    System.out.println("无效选项，请重新选择！");
            }
        }
    }

    // 查看所有宠物
    private static void showAllPets(Scanner scanner) {
        System.out.println("\n请选择排序方式：");
        System.out.println("1) 按价格排序");
        System.out.println("2) 按年龄排序");
        System.out.print("请输入选项: ");
        int sortChoice = scanner.nextInt();
        scanner.nextLine(); // 清除缓冲区

        String sql;
        switch (sortChoice) {
            case 1:
                sql = "SELECT * FROM pet ORDER BY price";
                break;
            case 2:
                sql = "SELECT * FROM pet ORDER BY age";
                break;
            default:
                System.out.println("无效选项，默认按价格排序！");
                sql = "SELECT * FROM pet ORDER BY price";
        }

        try (Connection conn = DriverManager.getConnection(URL, USER, PASSWORD);
             Statement stmt = conn.createStatement();
             ResultSet rs = stmt.executeQuery(sql)) {
            System.out.println("\n宠物列表：");
            while (rs.next()) {
                System.out.println("ID: " + rs.getInt("id") +
                        ", 主人ID: " + rs.getInt("owner_id") +
                        ", 昵称: " + rs.getString("name") +
                        ", 类型: " + rs.getString("type") +
                        ", 年龄: " + rs.getInt("age") +
                        ", 性别: " + rs.getString("gender") +
                        ", 价格: " + rs.getInt("price"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }



    //购买宠物
    private static void buyPets(Scanner scanner){
        System.out.print("请输入要购买的宠物ID: ");
        int petId = scanner.nextInt();
        scanner.nextLine(); // 清除缓冲区

        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        try {
            conn = DriverManager.getConnection(URL, USER, PASSWORD);

            // 查找宠物
            String sql = "SELECT price FROM pet WHERE id = ? AND owner_id IS NULL";
            pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1, petId);
            rs = pstmt.executeQuery();
            if (rs.next()) {
                int price = rs.getInt("price");

                // 检查用户积分是否足够
                sql = "SELECT points FROM p_user WHERE id = ?";
                pstmt = conn.prepareStatement(sql);
                pstmt.setInt(1, currentUserId);
                rs = pstmt.executeQuery();
                if (rs.next()) {
                    int points = rs.getInt("points");
                    if (points >= price) {
                        // 扣除用户积分
                        String sql2 = "UPDATE p_user SET points = points - ? WHERE id = ?";
                        pstmt = conn.prepareStatement(sql2);
                        pstmt.setInt(1,price);
                        pstmt.setInt(2, currentUserId);
                        pstmt.executeUpdate();

                        // 设置宠物的主人ID
                        String sql3 = "UPDATE pet SET owner_id = ? WHERE id = ?";
                        pstmt = conn.prepareStatement(sql3);
                        pstmt.setInt(1, currentUserId);
                        pstmt.setInt(2, petId);
                        pstmt.executeUpdate();

                        System.out.println("购买成功！");
                    } else {
                        System.out.println("积分不足，无法购买！");
                    }
                }
            } else {
                System.out.println("未找到该宠物或宠物已有主人！");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }





    // 添加宠物
    private static void addPet(Scanner scanner) {
        System.out.print("请输入宠物昵称: ");
        String name = scanner.nextLine();
        System.out.print("请输入宠物类型: ");
        String type = scanner.nextLine();
        System.out.print("请输入宠物年龄: ");
        int age = scanner.nextInt();
        scanner.nextLine();
        System.out.print("请输入宠物性别 (公/母): ");
        String gender = scanner.nextLine();
        System.out.println("请输入宠物价格: ");
        int price = scanner.nextInt();
        scanner.nextLine();

        String sql = "INSERT INTO pet (name, type, age, gender, price) VALUES (?, ?, ?, ?, ?)";
        try (Connection conn = DriverManager.getConnection(URL, USER, PASSWORD);
             PreparedStatement ps = conn.prepareStatement(sql)) {
            ps.setString(1, name);
            ps.setString(2, type);
            ps.setInt(3, age);
            ps.setString(4, gender);
            ps.setInt(5,price);
            int rows = ps.executeUpdate();
            if (rows > 0) {
                System.out.println("宠物添加成功！");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    // 删除宠物
    private static void deletePet(Scanner scanner) {
        System.out.print("请输入要删除的宠物ID: ");
        int id = scanner.nextInt();
        scanner.nextLine(); // 清除缓冲区

        String sql = "DELETE FROM pet WHERE id = ?";
        try (Connection conn = DriverManager.getConnection(URL, USER, PASSWORD);
             PreparedStatement ps = conn.prepareStatement(sql)) {
            ps.setInt(1, id);
            int rows = ps.executeUpdate();
            if (rows > 0) {
                System.out.println("宠物删除成功！");
            } else {
                System.out.println("未找到该宠物！");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    // 更新宠物信息
    private static void updatePet(Scanner scanner) {
        System.out.print("请输入要更新的宠物ID: ");
        int id = scanner.nextInt();
        scanner.nextLine();
        System.out.print("请输入宠物昵称: ");
        String name = scanner.nextLine();
        System.out.print("请输入宠物类型: ");
        String type = scanner.nextLine();
        System.out.print("请输入宠物年龄: ");
        int age = scanner.nextInt();
        scanner.nextLine();
        System.out.print("请输入宠物性别 (公/母): ");
        String gender = scanner.nextLine();
        System.out.println("请输入宠物价格: ");
        int price = scanner.nextInt();
        scanner.nextLine();

        String sql = "UPDATE pet SET name = ?, type = ?, age = ?, gender = ?,price = ? WHERE id = ? AND owner_id = ?";
        try (Connection conn = DriverManager.getConnection(URL, USER, PASSWORD);
             PreparedStatement ps = conn.prepareStatement(sql)) {
            ps.setString(1, name);
            ps.setString(2, type);
            ps.setInt(3, age);
            ps.setString(4, gender);
            ps.setInt(5, price);
            ps.setInt(6, id);
            ps.setInt(7, currentUserId);
            int rows = ps.executeUpdate();
            if (rows > 0) {
                System.out.println("宠物信息更新成功！");
            } else {
                System.out.println("未找到该宠物或无权更新！");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    // 查看所有用户（仅管理员）
    private static void showAllUsers() {
        String sql = "SELECT * FROM p_user";
        try (Connection conn = DriverManager.getConnection(URL, USER, PASSWORD);
             Statement stmt = conn.createStatement();
             ResultSet rs = stmt.executeQuery(sql)) {
            System.out.println("\n用户列表：");
            while (rs.next()) {
                System.out.println("ID: " + rs.getInt("id") +
                        ", 用户名: " + rs.getString("username") +
                        ", 积分: " + rs.getInt("points") +
                        ", 手机号: " + rs.getString("phone") +
                        ", 是否管理员: " + rs.getBoolean("is_admin"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

}
